import base64

import ddddocr
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait  # 这个是为显隐式等待提供方法的模块
from selenium.webdriver.support import expected_conditions as EC  # 这个是为显示等待提供定位功能的模块

options = webdriver.ChromeOptions()  # 创建谷歌浏览器的options对象来接收浏览器的相关设置

options.add_argument('--start-maximized')  # 最大化窗口
options.add_argument('--incognito')  # 无痕浏览
options.add_argument('--disable-extensions')  # 禁用浏览器的扩展程序,避免干扰网站的打开
options.add_experimental_option("detach", True)  # 禁止浏览器自动关闭
options.add_experimental_option('excludeSwitches', ['enable-automation'])
options.add_experimental_option('useAutomationExtension', False)

# options.add_argument('--headless')
# options.add_argument('user-agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"')
# options.add_argument('--disable-gpu')

driver = webdriver.Chrome(options)  # 创建谷歌浏览器驱动对象
driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
    'source': '''
    Object.defineProperty(navigator, 'webdriver',{get:() => false})
    '''
})

driver.get('https://captcha1.scrape.center/')

wait = WebDriverWait(driver, 60)  # # 设置等待时间

# titles = driver.find_elements(By.CLASS_NAME, 'm-b-sm')
# titles = wait.until(EC.presence_of_all_elements_located((By.CLASS_NAME, 'm-b-sm')))

username_inp, password_inp = wait.until(
    EC.presence_of_all_elements_located((By.CLASS_NAME, 'el-input__inner'))
)

username_inp.send_keys('admin')
password_inp.send_keys('admin')

wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '.el-button.el-button--primary'))).click()
# geetest_canvas_slice geetest_absolute 滑块图
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '.geetest_canvas_bg.geetest_absolute')))
slice_base64 = driver.execute_script(
    "return document.getElementsByClassName('geetest_canvas_slice')[0].toDataURL('image/png')"
).split(',')[1]
with open('slice.png', 'wb') as fp:
    fp.write(base64.b64decode(slice_base64))

# geetest_canvas_bg geetest_absolute 缺口背景图
# wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '.geetest_canvas_bg.geetest_absolute')))
bg_base64 = driver.execute_script(
    "return document.getElementsByClassName('geetest_canvas_bg')[0].toDataURL('image/png')"
).split(',')[1]
with open('bg.png', 'wb') as fp:
    fp.write(base64.b64decode(bg_base64))

# geetest_canvas_fullbg geetest_fade geetest_absolute 完整图
# wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '.geetest_canvas_fullbg.geetest_fade.geetest_absolute')))
fullbg_base64 = driver.execute_script(
    "return document.getElementsByClassName('geetest_canvas_fullbg')[0].toDataURL('image/png')"
).split(',')[1]
with open('fullbg.png', 'wb') as fp:
    fp.write(base64.b64decode(fullbg_base64))